module.exports = app => {
  const express = require('express')
  // express 的子路由
  const router = express.Router({
    mergeParams: true
  })

  // 导入模型
  // const Category = require('../../models/Category')

  // 创建分类
  router.post('/', async (req, res) => {
    console.log('post/')
    const model = await req.Model.create(req.body)
    res.send(model)
  })
  // 更新分类
  router.put('/:id', async (req, res) => {
    console.log('put/:id')
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.send(model)
  })
  // 删除分类
  router.delete('/:id', async (req, res) => {
    console.log('delete/:id')
    const model = await req.Model.findByIdAndDelete(req.params.id)


    if (model.icon) {
      console.log('delete:', req.params.id, model.icon)
      // __dirname + '/../../uploads
      var fs = require("fs");

      console.log("准备删除文件！");
      var iconurl = model.icon.slice(model.icon.indexOf('uploads'))
      fs.unlink(__dirname + '/../../' + iconurl, function (err) {
        if (err) {
          return console.error(err);
        }
        console.log("文件删除成功！");
      });
    }
    res.send({
      success: true
    })
  })
  // 批量查询分类列表
  router.get('/', async (req, res) => {
    // 'categories' => 'Category' 小写复数转换成首字母大写的类名
    // const modelName = require('inflection').classify(req.params.resource)

    // console.log('modelName:',modelName)
    // const Model = require(`../../models/${modelName}`)
    // populate("parent"),关联查询 返回 一个对象包含 parent所有信息 _id, name等

    const queryOptions = {}
    if (req.Model.modelName === 'Category') {
      queryOptions.populate = 'parent'
    }

    const items = await req.Model.find().setOptions(queryOptions).limit(10)
    res.send(items)
  })
  // 根据id 查询
  router.get('/:id', async (req, res) => {
    console.log('get/:id')
    const model = await req.Model.findById(req.params.id)
    res.send(model)
  })
  // 添加中间件 给req添加 Model 属性 req.Model
  app.use('/admin/api/rest/:resource', async (req, res, next) => {
    // 'categories' => 'Category' 小写复数转换成首字母大写的类名
    const modelName = require('inflection').classify(req.params.resource)
    console.log('modelName:', modelName)
    req.Model = require(`../../models/${modelName}`)
    next()
  }, router)

  const multer = require('multer')
  const upload = multer({ dest: __dirname + '/../../uploads' })
  // app.post('/admin/api/upload', async (req, res)=>{ })
  // 添加中间键 upload.single('file') 接收单个文件上传 , file 为前端上传的文件字段
  app.post('/admin/api/upload', upload.single('file'), async (req, res) => {
    const file = req.file
    file.url = `http://localhost:3000/uploads/${file.filename}`
    res.send(file)
  })
}